// pages/memberpay/paymethod.js
var pojo = "";
var conpons = "";
var zhifuqian = 0;
var needpay = "";
var cardlist = [];
var paymethod = 0;
var req = require('../../interfaceImpl.js');
var config = require('../../interfaceConfig.js');
var strAppCode = config.SmallApp;
var app =getApp()
var strCardNo ="";
var hasChooseSeat = [];
var reqPaySign = "" ;
var huiyuanprice ="";
var wxprice = "";
/** 
 * 需要一个目标日期，初始化时，先得出到当前时间还有剩余多少秒
 * 1.将秒数换成格式化输出为XX天XX小时XX分钟XX秒 XX
 * 2.提供一个时钟，每10ms运行一次，渲染时钟，再总ms数自减10
 * 3.剩余的秒次为零时，return，给出tips提示说，已经截止
 */

// 定义一个总毫秒数，以一分钟为例。TODO，传入一个时间点，转换成总毫秒数
var total_micro_second = 5 * 60 * 1000;

/* 毫秒级倒计时 */
function count_down(that) {
  // 渲染倒计时时钟
  that.setData({
    clock: date_format(total_micro_second)
  });

  if (total_micro_second <= 0) {
    that.setData({
      clock: "已经截止",
      issuccess: false,
    });
    // timeout则跳出递归
    return;
  }
  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 10;
    count_down(that);
  }
    , 10)
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));

  return min + "分" + sec + "秒";
}

// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    zhifuqian: zhifuqian
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    count_down(this);
  
    huiyuanprice = parseInt(options.huiyuanprice);
    wxprice = parseInt(options.wxprice);
    console.log(huiyuanprice)
    console.log()
    conpons = options.conpons;
    pojo = JSON.parse(options.pojo);
    needpay = options.needpay;
    console.log(needpay);
    console.log(conpons)
    console.log(pojo)
    hasChooseSeat = pojo.haschooseseat;
    this.setData({ pojo})
    return req.CardList(app.globalData.token).then(res => {
      console.log(res)
      cardlist = res.data.data;
      console.log(cardlist);
      var couarr = "";
      if(conpons.length>0){
        couarr = conpons.split(",").length
      }else{
        couarr =0;
      }
      if (cardlist.length > 0) {
        zhifuqian = (hasChooseSeat.length - couarr) * huiyuanprice ;
        this.setData({ hascard: true, zhifuqian })
        paymethod = 0;
        for (var i = 0; i < cardlist.length; i++) {
          cardlist[i].cardNostart = cardlist[i].Mcode.substring(0, 4) + "****" + cardlist[i].Mcode.substr(cardlist[i].Mcode.length - 2, cardlist[i].Mcode.length)
        }
    
      }else{
        zhifuqian = (hasChooseSeat.length - couarr) * wxprice;
      }   

      this.setData({ cardlist: cardlist})
    })

  },
    order_detail:function(){
      var that = this;

      //没卖品 直接支付
      if (paymethod === ! '') {
        wx.showModal({
          title: '提示',
          content: '请选择支付方式',
        })
      } else if (paymethod == 'wxpay') {
        //TODO 微信支付
        if (conpons == "") {
          zhifuqian = zhifuqian;
        } else {
          var conponsarr ="";
          if(conpons == ""){
            conponsarr = 0;
          }else{
            conponsarr = conpons.split(",").length;
          }

          if (conponsarr.length < hasChooseSeat.length) {
            //选的卷 比选的座少
            zhifuqian = (hasChooseSeat.length - conponsarr) * wxprice
          } else if (conponsarr == hasChooseSeat.length) {
            //支付0元钱
            var paysign = "strAppCode=" + strAppCode + "OrderTicketID=" + pojo.OrderTicketID + "wxopenID=ooORTwu9F9-roa7PI74rHIWfjuvA" + "mphone=" + app.globalData.loginuserinfo.mobile + "" + "LinkTelcode=" + app.globalData.loginuserinfo.mobile + "" + "pamounts=" + zhifuqian + "" + "coupons=" + conpons + "";
            return req.GetSignStr(paysign).then(res => {
              if (res.data.success) {
                reqPaySign = res.data.data;
              }
            }).then(() => {
              return req.SellTicketB(strAppCode, pojo.OrderTicketID, "ooORTwu9F9-roa7PI74rHIWfjuvA", app.globalData.loginuserinfo.mobile, app.globalData.loginuserinfo.mobile, "0", conpons, reqPaySign, app.globalData.token)
            }).then(res => {
              console.log(res)
              var result = res.data.data
              if (res.data.success) {
                setTimeout(function () {
                  // 放在最后--
                  wx.hideLoading();
                }
                  , 1000)

                wx.showToast({
                  title: '支付成功',
                  success: function () {
                    setTimeout(function () {
                      // 放在最后--
                      wx.reLaunch({
                        url: '../member/buyTicketsOrder',
                      })
                    }
                      , 3000)


                  }
                })

              } else {
                wx.showModal({
                  title: '提示',
                  content: '支付失败',
                })
                setTimeout(function () {
                  // 放在最后--
                  wx.hideLoading();
                }
                  , 1600)
                return false;
              }
            })
          } else {
            //异常支付
            wx.showModal({
              title: '提示',
              content: '您的支付有异常',
            })
            return false
          }

        }

        var paysign = "strAppCode=" + strAppCode + "OrderTicketID=" + pojo.OrderTicketID + "wxopenID=ooORTwu9F9-roa7PI74rHIWfjuvA" + "mphone=" + app.globalData.loginuserinfo.mobile + "" + "LinkTelcode=" + app.globalData.loginuserinfo.mobile + "" + "pamounts=" + zhifuqian + "" + "coupons=" + conpons + "";
        return req.GetSignStr(paysign).then(res => {
          if (res.data.success) {
            reqPaySign = res.data.data;

          }
        }).then(() => {
          return req.GetMiniAppPaySign(strAppCode, pojo.OrderTicketID, "ooORTwu9F9-roa7PI74rHIWfjuvA", app.globalData.loginuserinfo.mobile, app.globalData.loginuserinfo.mobile, zhifuqian, conpons, reqPaySign, app.globalData.token).then(res => {

            console.log(res)
            var pay = res.data
            //发起支付   
            var timeStamp = pay.TimeStamp;
            console.log("timeStamp:" + timeStamp)
            var packages = pay.Package;
            console.log("package:" + packages)
            var nonceStr = pay.NonceStr;
            console.log("nonceStr:" + nonceStr)
            var paySign = pay.PaySign;
            console.log("paySign:" + paySign)
            var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": "MD5", "nonceStr": nonceStr };
            //调用支付
            // pay(param)
            console.log("支付")
            wx.requestPayment({
              timeStamp: param.timeStamp,
              nonceStr: param.nonceStr,
              package: param.package,
              signType: param.signType,
              paySign: param.paySign,
              success: function (res) {
                // 业务逻辑
                console.log("支付成功")
                wx.showToast({
                  title: '支付成功',
                  success: function () {
                    setTimeout(function () {
                      // 放在最后--
                      wx.reLaunch({
                        url: '../member/buyTicketsOrder',
                      })
                    }
                      , 3000)


                  }
                })


              }, fail: function (error) {
                console.log(error)

              }
            })
          })
        })


      }
      else {  //TODO 会员卡支付
        wx.showLoading({
          title: '支付中',
          mask: true
        })
   
      
        strCardNo = cardlist[paymethod].Mcode;
        if (zhifuqian > cardlist[paymethod].Balance) {
          wx.showModal({
            title: '提示',
            content: '卡内余额不足',
          })
          return false;
        }
        var couarr = "";
        if (conpons.length > 0) {
          couarr = conpons.split(",").length
        } else {
          couarr = 0;
        }
      
          zhifuqian = (hasChooseSeat.length - couarr) * huiyuanprice;
          console.log("会员卡支付金额"+zhifuqian)
        var paysign = "strAppCode=" + strAppCode + "OrderTicketID=" + pojo.OrderTicketID + "wxopenID=ooORTwu9F9-roa7PI74rHIWfjuvA" + "mphone=" + app.globalData.loginuserinfo.mobile + "" + "strCardNo=" + strCardNo + "" + "LinkTelcode=" + app.globalData.loginuserinfo.mobile + "" + "coupons=" + conpons + "" + "PayTotalPrice=" + zhifuqian;
        return req.GetSignStr(paysign).then(res => {
          if (res.data.success) {
            reqPaySign = res.data.data;
          }
        }).then(() => {
          // 发起支付
          console.log('支付金额' + zhifuqian)
          return req.SellTicketA(strAppCode, pojo.OrderTicketID, "ooORTwu9F9-roa7PI74rHIWfjuvA", app.globalData.loginuserinfo.mobile, strCardNo, app.globalData.loginuserinfo.mobile, conpons, zhifuqian, reqPaySign, app.globalData.token).then(res => {
            console.log(res)
            var result = res.data.data
            // if (res.data.success) {
            //跳转到支付成功页面
            if (res.data.success) {
              setTimeout(function () {
                // 放在最后--
                wx.hideLoading();
              }
                , 1000)

              wx.showToast({
                title: '支付成功',
                success: function () {
                  setTimeout(function () {
                    // 放在最后--
                    wx.reLaunch({
                      url: '../member/buyTicketsOrder',
                    })
                  }
                    , 3000)

                }
              })

            } else {
              wx.showModal({
                title: '提示',
                content: '会员卡支付失败',
              })
              setTimeout(function () {
                // 放在最后--
                wx.hideLoading();
              }
                , 1600)
              return false;
            }

          })
        })
      }

    },
    radioChange: function (e) {
      console.log(e)
      paymethod = e.detail.value;
      if (e.detail.value === ""){
        var conponsarr = "";
        if (conpons == "") {
          conponsarr = 0;
        } else {
          conponsarr = conpons.split(",").length;
        }
        zhifuqian = zhifuqian = (hasChooseSeat.length - conponsarr) * wxprice;
        this.setData({ zhifuqian })
      }
      else if (e.detail.value === "wxpay"){
        var conponsarr = "";
        if (conpons == "") {
          conponsarr = 0;
        } else {
          conponsarr = conpons.split(",").length;
        }
        console.log(conponsarr)
        zhifuqian = (hasChooseSeat.length - conponsarr) * wxprice;
        this.setData({ zhifuqian })
      }else{
        var conponsarr = "";
        if (conpons == "") {
          conponsarr = 0;
        } else {
          conponsarr = conpons.split(",").length;
        }

        console.log(conponsarr)
        zhifuqian  = (hasChooseSeat.length - conponsarr) * huiyuanprice;
        this.setData({ zhifuqian })
      }
    }
})